﻿using System.Net;
using System.Net.Mail;

namespace OpenHunauEleEmailSender
{
	public class SendMailSys
	{
		private static readonly SmtpClient client;
		static SendMailSys()
		{
			client = new()
			{
				Credentials = new NetworkCredential(Config.Inst.SenderEmailAddress, Config.Inst.SenderEmailPassword),
				Host = Config.Inst.SenderEmailServerHost,
				Port = Config.Inst.SenderEmailServerPort
			};
		}
		public static bool Init()
		{
			client.SendCompleted += (sender, e) =>
			{
				if (e.Error != null)
				{
					Console.WriteLine("(回调)邮件发送失败: " + e.Error.Message);
				}
				else
				{
					Console.WriteLine("(回调)邮件发送成功");
				}
			};
			return SendMail("启动通知", "湖南农业大学开源电费平台自动邮件通知服务已启动！", new List<string> { Config.Inst.SenderEmailAddress });
		}
		public static bool SendMail(string title, string content, List<string> tos)
		{
			try
			{
				MailMessage message = new();
				//添加邮件接收地址
				foreach (var item in tos)
				{
					if (!string.IsNullOrEmpty(item) && item != "excample@email.com")
						message.To.Add(item.Trim());
				}
				message.From = new MailAddress(Config.Inst.SenderEmailAddress, "电费服务提醒员", System.Text.Encoding.UTF8);//设置发件人地址，发件人姓名，以及编码
				message.Subject = title;// 邮件标题
				message.SubjectEncoding = System.Text.Encoding.UTF8;// 邮件标题编码
				message.Body = content;// 邮件内容
				message.BodyEncoding = System.Text.Encoding.UTF8;// 邮件内内容的编码
				message.IsBodyHtml = false;// 设置邮件是否为HTML邮件
				message.Priority = MailPriority.High;// 设置邮件优先级
													 //发送邮件
				client.Send(message);
				//发送成功
				Console.WriteLine("邮件发送成功");
				return true;
			}
			catch (Exception e)
			{
				//发送失败
				Console.WriteLine("错误信息: " + e.Message);
				return false;
			}
		}
	}
}
